/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package TimeRecording.TimeClockServer;

/**
 * A generic cyclical log.
 *
 * @author david
 */
public class CyclicalLog<T> {

    private int maxSize = 100;
    private int head = 0; // oldest element
    private int tail = 0; // newest element
    private int size = 0;

    private Object[] elements;

    public CyclicalLog(int maxSize) {
        this.maxSize = maxSize;
        elements = new Object[maxSize];
    }

    public void addElement(T element) {
        if (size == maxSize) {
            head = increment(head);
            size--;
        }
        elements[tail] = element;
        tail = increment(tail);
        size++;
    }

    public T getElement(int index) {
        if (index < size) {
            return (T)elements[wrap(index + head)];
        } else {
            return null;
        }
    }

    public int size() {
        return size;
    }

    private int increment(int pointer) {
        return wrap(++pointer);
    }

    private int wrap(int pointer) {
        return pointer % maxSize;
    }
}
